package com.mobilezu.mobile.android.mobile4s.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBHelper {
	private SQLiteDatabase m_SQLiteDatabase = null;
	private Context mContext = null;
	private static String dbFullPath;

	public DBHelper(Context context, String fullPath) {
		this.mContext = context;
		dbFullPath = fullPath;
	}

	public Cursor query(String sql) {
		Cursor cursor = null;
		dbOpen();
		if (m_SQLiteDatabase != null && m_SQLiteDatabase.isOpen()) {
			cursor = m_SQLiteDatabase.rawQuery(sql, null);
			if (cursor != null && cursor.getCount() > 0) {
				cursor.moveToFirst();
			} else {
				if (cursor != null) {
					cursor.close();
					cursor = null;
				}
			}
		}
		dbClose();
		return cursor;
	}

	public void exec(String sql) {
		dbOpen();
		if (m_SQLiteDatabase != null && m_SQLiteDatabase.isOpen()) {
			m_SQLiteDatabase.execSQL(sql);
		}
		dbClose();
	}

	public int delete(String tableName, String whereClause, String[] whereArgs) {
		int ret = -1;
		dbOpen();
		if (m_SQLiteDatabase != null && m_SQLiteDatabase.isOpen()) {
			ret = m_SQLiteDatabase.delete(tableName, whereClause, whereArgs);
		}
		dbClose();
		return ret;
	}

	public int queryCount(String sql) {
		Cursor cur = query(sql);
		int ret = 0;
		if (cur != null) {
			ret = cur.getCount();
			cur.close();
		}
		return ret;
	}

	private void dbClose() {
		if (m_SQLiteDatabase != null && m_SQLiteDatabase.isOpen()) {
			m_SQLiteDatabase.close();
		}
	}

	private void dbOpen() {
		m_SQLiteDatabase = mContext.openOrCreateDatabase(dbFullPath,
				Context.MODE_PRIVATE, null);
	}

	@SuppressWarnings("finally")
	public static SQLiteDatabase beginTransaction(Context context,String databaseFullPath) {
		SQLiteDatabase ret = null;
		try {
			SQLiteDatabase db = context.openOrCreateDatabase(databaseFullPath,
					Context.MODE_PRIVATE, null);
			db.beginTransaction();
			ret = db;
		} finally {
			return ret;
		}

	}

	@SuppressWarnings("finally")
	public static boolean exec(SQLiteDatabase db, String sql) {
		boolean ret = false;
		if (db == null)
			return ret;
		try {
			db.execSQL(sql);
			ret = true;
		} finally {
			return ret;
		}

	}

	public static void endTransaction(SQLiteDatabase db) {
		if (db != null)
			db.endTransaction();
	}
}